<template>
  <a-card class="article-manage_notice">
    <a-row>
      <a-col :span="12">
        <a-button type="primary" @click="linkColArticle">关联文章</a-button>
      </a-col>
      <a-col :span="12">
        <a-row type="flex" justify="end">
          <a-select
            class="article-type"
            placeholder="全部类型"
            allow-clear
            v-model:value="articleType.type"
            @change="resetPage"
          >
            <a-select-option value="1">平台文章</a-select-option>
            <a-select-option value="2">外部链接</a-select-option>
          </a-select>
          <a-input-search
            v-model:value="articleType.title"
            style="width: 210px"
            placeholder="请输入文章名称"
            @search="resetPage"
          />
        </a-row>
      </a-col>
    </a-row>
    <div class="line"></div>
    <a-row type="flex">
      <a-col :span="3">
        <h3 class="menu-title">公告栏目</h3>
        <!-- <a-input-search v-model:value="menuName" style="margin-bottom: 8px" placeholder="Search" /> -->
        <a-tree
          v-model:expandedKeys="noticeList.expandedKeys"
          :autoExpandParent="noticeList.autoExpandParent"
          :replaceFields="{ children: 'children', title: 'columnName', key: 'id' }"
          :tree-data="gData"
        >
          <!-- @select="menuSearch" -->
          <!-- <template #title="{ title }"> -->
          <!--<span v-if="title.indexOf(menuName) > -1">
              {{ title.substr(0, title.indexOf(menuName)) }}
              <span style="color: #f50">{{ menuName }}</span>
              {{ title.substr(title.indexOf(menuName) + menuName.length) }}
            </span>
            <span v-else>{{ title }}</span> -->
          <!-- {{ title }} -->
          <!-- </template> -->
        </a-tree>
      </a-col>
      <a-col :span="21" style="padding: 0 20px">
        <a-table :columns="columns" :data-source="state.dataSource" rowKey="id" :pagination="false">
          <!-- 浏览次数 -->
          <template #scanNum="{ record }">
            <span>
              <i class="iconfont icon-guankanshu-16px"></i>
              {{ record.scanNum || 0 }}
            </span>
          </template>

          <!-- 同意次数 -->
          <template #thumbsUp="{ record }">
            <span>
              <i class="iconfont icon-dianzan-16px"></i>
              {{ record.thumbsUp || 0 }}
            </span>
          </template>

          <!-- 反对次数 -->
          <template #thumbsDown="{ record }">
            <span>
              <i class="iconfont icon-fandui-32px"></i>
              {{ record.thumbsDown || 0 }}
            </span>
          </template>

          <template #sequence="{ record }">
            <a-input-number
              @change="changeSort($event, record)"
              @blur="confirmChangeSort"
              :value="record.sequence"
            ></a-input-number>
          </template>

          <!-- 操作 -->
          <template #handler="{ record }">
            <!-- <a @click="remove(record)">转移</a> -->
            <!-- <span style="color: #1890ff; margin: 0 6px">|</span> -->
            <a @click="dissociated(record)">解除关联</a>
          </template>
        </a-table>
        <a-row style="margin-top: 20px" type="flex" justify="end">
          <a-pagination
            show-quick-jumper
            showSizeChanger
            v-model:pageSize="pagination.limit"
            v-model:current="pagination.page"
            :total="pagination.total"
            :showTotal="() => `共 ${pagination.total} 条数据`"
            @change="getList"
            @showSizeChange="getList"
          />
        </a-row>
      </a-col>
    </a-row>
    <a-modal v-bind="colArticleModal" @ok="validLinkArticle" @cancel="closeColArticle">
      <h2 style="font-size: 16px">关联文章</h2>
      <list-transfer
        v-if="colArticleModal.visible"
        :selectList="tags"
        select-placeholder="选择文章标签"
        :dataSource="articleList.dataSource"
        v-model:inputValue="searchArticleInfo.keywords"
        v-model:selectValue="searchArticleInfo.labelId"
        v-model:value="linkArticleKey.articleIds"
        @select="confirmGetTagList"
        @scroll="scollGetArticle"
      ></list-transfer>
      <h2 style="font-size: 16px">关联栏目</h2>
      <div>
        <a-transfer
          v-if="colArticleModal.visible"
          class="link-notice_transfer"
          :data-source="noticeCol"
          :target-keys="linkArticleKey.columnIds"
          :render="item => item.columnName"
          @change="changeNotice"
        />
      </div>
    </a-modal>
  </a-card>
</template>

<script>
import { reactive, defineComponent, ref, toRaw, watch } from 'vue';
import { findChildrenList } from '@/utils';
import { message } from 'ant-design-vue';
import ListTransfer from '@/components/list-transfer';
import {
  apiGetArticleColList,
  apiGetColumnList,
  apiGetArticleTagList,
  apiAddRelationdArticle,
  apiGetArticleList,
  apiDissociated,
  apiEditRelationdArticle,
} from '@/api/articleManage';
import { concatIds, disposeTransferList } from '@/utils/helper';
// const getParentKey = (key, tree) => {
//   let parentKey;

//   for (let i = 0; i < tree.length; i++) {
//     const node = tree[i];

//     if (node.children) {
//       if (node.children.some(item => item.key === key)) {
//         parentKey = node.key;
//       } else if (getParentKey(key, node.children)) {
//         parentKey = getParentKey(key, node.children);
//       }
//     }
//   }

//   return parentKey;
// };

const columns = [
  {
    title: '关联文章',
    dataIndex: 'articleName',
    width: '30%',
  },
  {
    title: '栏目名称',
    dataIndex: 'columnName',
  },
  {
    title: '浏览次数',
    dataIndex: 'scanNum',
    slots: {
      customRender: 'scanNum',
    },
  },
  {
    title: '赞同数',
    dataIndex: 'thumbsUp',
    slots: {
      customRender: 'thumbsUp',
    },
  },
  {
    title: '反对数',
    dataIndex: 'thumbsDown',
    slots: {
      customRender: 'thumbsDown',
    },
  },
  {
    title: '排序',
    dataIndex: 'sequence',
    width: '8%',
    slots: {
      customRender: 'sequence',
    },
  },
  {
    title: '操作',
    dataIndex: 'handler',
    slots: {
      customRender: 'handler',
    },
  },
];

export default defineComponent({
  name: 'menuHelp',
  setup() {
    let isLoading = false;

    // 文章类型过滤
    const articleType = reactive({
      type: undefined,
      title: '',
    });

    // 菜单路由相关数据
    const noticeList = reactive({
      loading: false, // 加载
      dataSource: [], // 选中
      autoExpandParent: true, // 展开
      expandedKeys: [], // 选中值
    });
    const noticeCol = ref([]);
    // 展示的树组件数据，已递归
    const gData = ref([]);

    /**
     * 获取栏目数据
     **/
    const confirmGetColumn = async () => {
      try {
        noticeList.loading = true;
        const res = await apiGetColumnList({ type: 2 });
        noticeCol.value = disposeTransferList(res.list, 'columnName', 'id');
        noticeList.dataSource = res.list;
        gData.value = findChildrenList(noticeList.dataSource, 0);
      } finally {
        noticeList.loading = false;
      }
    };
    confirmGetColumn();

    // 注释为搜索树组件
    // const menuName = ref('');
    // const searchMenu = menuName => {
    //   console.log(menuName.value);
    //   console.log('use value', menuName);
    // };

    // watch(expandedKeys, () => {
    //   autoExpandParent.value = false;
    // });

    // watch(menuName, value => {
    //   const expanded = noticeList.dataSource
    //     .map(item => {
    //       if (item.title.indexOf(value) > -1) {
    //         return getParentKey(item.key, gData.value);
    //       }
    //       return null;
    //     })
    //     .filter((item, i, self) => item && self.indexOf(item) === i);
    //   expandedKeys.value = expanded;
    //   menuName.value = value;
    //   autoExpandParent.value = true;
    // });

    /**
     * 重置页码并获取数据
     **/
    const resetPage = () => {
      pagination.page = 1;
      getList();
    };

    // const menuSearch = node => {
    //   console.log('选择路由菜单', node);
    // };

    // 分页数据
    const pagination = reactive({ limit: 10, page: 1, total: 0 });

    // 存放列表数据
    const state = reactive({ dataSource: [], loading: false });

    /**
     * 获取列表
     **/
    const getList = async () => {
      try {
        state.loading = true;
        const { page } = await apiGetArticleColList({
          page: pagination.page,
          limit: pagination.limit,
          articleType: articleType.type,
          keywords: articleType.title,
          type: 3,
        });
        state.dataSource = page.list;
        pagination.total = page.total;
      } finally {
        state.loading = false;
      }
    };
    getList();

    /**
     * 修改排序
     **/
    const sequence = { number: '', info: {} };
    const changeSort = (e, row) => {
      sequence.number = e;
      sequence.info = toRaw(row);
    };

    /**
     * 确认修改
     **/
    const confirmChangeSort = () => {
      if (!sequence.number) return;
      apiEditRelationdArticle({
        sequence: sequence.number,
        articleId: sequence.info.id,
        columnId: sequence.info.columnId,
        type: 3,
      }).then(() => {
        getList();
        sequence.number = '';
        sequence.info = {};
      });
    };

    /**
     * 解除关联
     **/
    const dissociated = async form => {
      try {
        const { columnId, id } = form;
        await apiDissociated({ type: 3, columnId, articleId: id });
        message.success('解除成功');
        getList();
      } catch (error) {
        console.log(error);
      }
    };

    /**
     * 获取标签列表
     **/
    const tags = ref([]);
    const confirmGetTagList = (keywords = '') => {
      apiGetArticleTagList({ keywords }).then(res => {
        tags.value = res.list;
      });
    };

    const colArticleModal = reactive({ visible: false, title: '关联文章', width: 800 });
    const linkColArticle = () => {
      colArticleModal.visible = true;
    };

    /**
     * 存储关联文章所需要的数据
     **/
    const linkArticleKey = reactive({ articleIds: [], columnIds: [] });

    /**
     * 更改栏目
     **/
    const changeNotice = keys => {
      linkArticleKey.columnIds = keys;
    };

    /**
     * 关闭关联文章弹窗
     **/
    const closeColArticle = () => {
      colArticleModal.visible = false;
      linkArticleKey.articleIds = [];
      linkArticleKey.columnIds = [];
    };

    /**
     * 校验关联文章
     **/
    const validLinkArticle = () => {
      if (!linkArticleKey.articleIds.length || !linkArticleKey.columnIds.length) {
        return message.error('文章或栏目不能为空');
      } else {
        confirmLinkArticle();
      }
    };

    /**
     * 关联文章
     **/
    const confirmLinkArticle = async () => {
      if (isLoading) return;

      const articleIds = concatIds(linkArticleKey.articleIds);
      const columnIds = concatIds(linkArticleKey.columnIds);
      try {
        isLoading = true;
        await apiAddRelationdArticle({ articleIds, columnIds, type: 3 });
        getList();
        closeColArticle();
        message.success('关联成功');
      } finally {
        isLoading = false;
      }
    };

    /**
     * 获取所有文章列表
     **/
    const articleList = reactive({
      page: 1,
      limit: 10,
      isAll: false,
      loading: false,
      dataSource: [],
    });

    /**
     * 将已经选中的选项筛选出
     **/
    const disposeSelectList = (list, selectValue) => {
      const selectList = [];
      list.forEach(item => {
        const selectItem = selectValue.find(value => item.id === +value);
        if (selectItem) {
          selectList.push(item);
        }
      });
      return selectList;
    };

    /**
     * 过滤已经选中的元素，避免重复添加
     **/
    const filterSelect = (list, selectIds) =>
      list.filter(item => !selectIds.some(articleId => +articleId === item.id));

    /**
     * 获取文章列表
     **/
    const searchArticleInfo = reactive({ keywords: '', labelId: undefined });
    const confirmGetArticle = async () => {
      try {
        articleList.loading = true;
        const { page } = await apiGetArticleList({
          page: articleList.page,
          limit: articleList.limit,
          labelId: searchArticleInfo.labelId,
          keywords: searchArticleInfo.keywords,
        });

        // 保存已选中的列表元素，即使重新调用接口，但是已选中的列表元素不可删除，否则会出现选中后更新搜索条件，已选中的选项被清空
        const selectList = disposeSelectList(articleList.dataSource, linkArticleKey.articleIds);
        // 过滤选中列表中的元素，否则可能存在左右两边均有出现的可能
        const list = filterSelect(page.list, linkArticleKey.articleIds);

        articleList.dataSource = disposeTransferList([...selectList, ...list], 'articleName', 'id');
      } finally {
        articleList.loading = false;
      }
    };
    confirmGetArticle();

    /**
     * 滚动事件
     **/
    const scollGetArticle = args => {
      const clientHeight = args[1].target.clientHeight;
      const scrollTop = args[1].target.scrollTop;
      const scrollHeight = args[1].target.scrollHeight;
      if (clientHeight + scrollTop === scrollHeight && !articleList.isAll) {
        articleList.page++;
        confirmScroll();
      }
    };

    /**
     * 滚动获取数据
     **/
    const confirmScroll = async () => {
      try {
        articleList.loading = true;
        const { page } = await apiGetArticleList({
          page: articleList.page,
          limit: articleList.limit,
          labelId: searchArticleInfo.labelId,
          keywords: searchArticleInfo.keywords,
        });
        const list = filterSelect(page.list, linkArticleKey.articleIds);
        articleList.dataSource = disposeTransferList(
          [...articleList.dataSource, ...list],
          'articleName',
          'id',
        );
        if (page.list.length < articleList.limit) {
          articleList.isAll = true;
        }
      } finally {
        articleList.loading = false;
      }
    };

    watch(searchArticleInfo, () => {
      articleList.page = 1;
      articleList.isAll = false;
      confirmGetArticle();
    });

    return {
      articleList,
      articleType,
      linkArticleKey,
      resetPage,
      confirmGetArticle,
      noticeCol,
      // menuName,
      // searchMenu,
      // autoExpandParent,
      noticeList,
      gData,
      tags,
      // menuSearch,
      columns,
      state,
      changeSort,
      confirmChangeSort,
      dissociated,
      validLinkArticle,
      linkColArticle,
      colArticleModal,
      changeNotice,
      pagination,
      confirmGetTagList,
      getList,
      searchArticleInfo,
      closeColArticle,
      scollGetArticle,
    };
  },
  components: {
    ListTransfer,
  },
});
</script>
<style lang="less">
.article-manage_notice {
  .article-type {
    width: 150px;
    margin-right: 10px;
  }
  .line {
    margin: 10px 0;
    border-top: 1px dashed #eee;
  }
  .menu-title {
    font-weight: 700;
    font-size: 14px;
  }
}
.link-notice_transfer {
  .ant-transfer-list {
    width: 300px;
    height: 300px;
  }
  .ant-transfer-list-body-search-wrapper {
    left: 128px;
    width: 60%;
    .ant-input {
      height: 24px;
    }
    .ant-transfer-list-search-action {
      top: 8px;
    }
  }
  .ant-transfer-list:last-child {
    .ant-transfer-list-body {
      padding: 0;
    }
    .ant-transfer-list-body-search-wrapper {
      display: none;
    }
  }
}
</style>
